package com.qfedu.openplateform.gateway.filter;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * 时间过滤器的作用就是请求 必须加上时间 time
 * /sztest?time=2021-08-27 10:59:39sign=A23B2AC0D7AA2CF89C825BB596140D9A&token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTYzMDAzMjc5MiwiZXhwIjoxNjMwMDM2MzkyLCJ1c2VybmFtZSI6ImFkbWluIn0.8h1OyNVuSNn0MuS0CWpogz17Ttxr8frIIhMr-SOpuOo
 *
 * 在此过滤中  获取 time 和当前 的系统时间比较，如果时间超过 60s 就要拦截，没有超过 60s 放行
 *
 */
public class TimerFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String time = request.getParameter("time");
        System.out.println(time);
        if (time != null && time != ""){
            Date nowTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = formatter.parse(time);
            long times = (nowTime.getTime() - startTime.getTime()) / 1000; // 时间差 单位是秒

            System.out.println("time1" + nowTime);
            System.out.println("time2" + startTime);

            System.out.println(times);
            if (times > 0 ) {
                if (times < 60 * 10) {
                    return true;
                }
            }
        }
        response.setContentType("application/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.SYSTEMPARAM_IDEMPOTENTS_ERROR);
        bean.setMessage("响应超时");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
